package com.sum.tea.rongrui

import android.view.WindowManager

import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.lifecycle.Observer
import com.example.lib_rongrui.RrReader
import com.sum.common.base.BaseMvvmActivity
import com.sum.tea.R
import com.sum.tea.databinding.ScanViewBinding
import com.sum.tea.rongrui.viewmodel.ScanViewViewModel

class ScanViewActivity : BaseMvvmActivity<ScanViewBinding, ScanViewViewModel>(), View.OnClickListener {

    private lateinit var binding: ScanViewBinding
    private lateinit var viewModel: ScanViewViewModel

    // Arrays for spinners
    private val strBand = arrayOf("Chinese band2", "US band", "Korean band", "EU band", "Chinese band1", "ALL band")
    private lateinit var strProfile: Array<String>
    private lateinit var strRange: Array<String>

    override fun initView(savedInstanceState: Bundle?) {
        binding = mBinding
        viewModel = mViewModel
        window.setFlags(
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
        )

        initView()
        setupObservers()

        when (viewModel.ModuleType) {
            0 -> {
                val param = RrReader.rrlib.GetInventoryPatameter()
                param.Session = 0
                RrReader.rrlib.SetInventoryPatameter(param)
                viewModel.readParam()
            }
            1 -> {
                val param = RrReader.rrlib.GetInventoryPatameter()
                param.Session = 1
                RrReader.rrlib.SetInventoryPatameter(param)
                viewModel.readParam()
            }
            2 -> {
                val param = RrReader.rrlib.GetInventoryPatameter()
                param.Session = 254
                RrReader.rrlib.SetInventoryPatameter(param)
                viewModel.readParam()
            }
            3 -> {
                val param = RrReader.rrlib.GetInventoryPatameter()
                param.Session = 1
                RrReader.rrlib.SetInventoryPatameter(param)
                viewModel.readParam()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        when (Connect232Activity.baud) {
            57600 -> viewModel.baudRateSelection.value = 0
            115200 -> viewModel.baudRateSelection.value = 1
        }

        when (viewModel.ModuleType) {
            0 -> {
                viewModel.readParam()
                viewModel.readInformation()
                viewModel.getRangeControl()
            }
            1 -> {
                viewModel.readParam()
                viewModel.readInformation()
                viewModel.readProfile()
                viewModel.readCheckAnt()
            }
            2 -> {
                viewModel.readParam()
                viewModel.readInformation()
                viewModel.readFocus()
                viewModel.readProfile()
                viewModel.readCheckAnt()
            }
            3 -> {
                viewModel.readParam()
                viewModel.readInformation()
                viewModel.readProfile()
            }
        }
    }

    private fun initView() {
        // Initialize UI components and set up listeners

        // Temperature and Loss TextViews
        binding.txtTempe.text = ""
        binding.txtLoss.text = ""
        binding.tvRuntime.setText("")

        // Buttons
        binding.btReadtemp.setOnClickListener(this)
        binding.btReadloss.setOnClickListener(this)
        binding.proSetting.setOnClickListener(this)
        binding.proRead.setOnClickListener(this)
        binding.ivtRead.setOnClickListener(this)
        binding.ivtSetting.setOnClickListener(this)
        binding.ivtOpen.setOnClickListener(this)
        binding.ivtClose.setOnClickListener(this)
        binding.btAnswer.setOnClickListener(this)
        binding.btActive.setOnClickListener(this)
        binding.btSetBdRate.setOnClickListener(this)
        binding.btSetantcheck.setOnClickListener(this)
        binding.btGetantcheck.setOnClickListener(this)
        binding.btSetFocus.setOnClickListener(this)
        binding.btGetFocus.setOnClickListener(this)
        binding.btSetProfile.setOnClickListener(this)
        binding.btGetRange.setOnClickListener(this)
        binding.btSetRange.setOnClickListener(this)

        // TextViews
        binding.version.text = ""
        binding.paramResult.text = ""

        // Spinners
        setupSpinners()

        // Layouts visibility
        binding.linetagfocus.visibility = View.GONE
        binding.lineprogile.visibility = View.GONE
        binding.linerange.visibility = View.GONE
        binding.lineloss.visibility = View.GONE
        binding.linecheckant.visibility = View.GONE

        // Determine ModuleType and set up profiles
        setupModuleType()
    }

    private fun setupSpinners() {
        // Power Spinner
        ArrayAdapter.createFromResource(
            this,
            R.array.Power_select,
            android.R.layout.simple_spinner_item
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.powerSpinner.adapter = adapter
        }
        binding.powerSpinner.setSelection(33, false)

        // Time Spinner
        val strTime = Array(256) { index -> "${index}*100ms" }
        ArrayAdapter(
            this,
            android.R.layout.simple_spinner_item,
            strTime
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.timeSpinner.adapter = adapter
        }
        binding.timeSpinner.setSelection(50, false)

        // Band Spinner
        ArrayAdapter(
            this,
            android.R.layout.simple_spinner_item,
            strBand
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.bandSpinner.adapter = adapter
        }
        binding.bandSpinner.setSelection(1, false)

        binding.bandSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>, view: View?,
                position: Int, id: Long
            ) {
                when (position) {
                    0 -> viewModel.setFre(1)
                    1 -> viewModel.setFre(2)
                    2 -> viewModel.setFre(3)
                    3 -> viewModel.setFre(4)
                    4 -> viewModel.setFre(8)
                    5 -> viewModel.setFre(0)
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>) {}
        }

        // JG Time Spinner
        val strJgTime = Array(7) { index -> "${index * 10}ms" }
        ArrayAdapter(
            this,
            android.R.layout.simple_spinner_item,
            strJgTime
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.jgTimeSpinner.adapter = adapter
        }
        binding.jgTimeSpinner.setSelection(3, false)

        // QValue Spinner
        ArrayAdapter.createFromResource(
            this,
            R.array.men_q,
            android.R.layout.simple_spinner_item
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.qvalueSpinner.adapter = adapter
        }
        binding.qvalueSpinner.setSelection(6, true)

        // Session Spinner
        ArrayAdapter.createFromResource(
            this,
            R.array.men_s,
            android.R.layout.simple_spinner_item
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.sessionSpinner.adapter = adapter
        }
        binding.sessionSpinner.setSelection(5, true)

        // TID Address and Length Spinners
        ArrayAdapter.createFromResource(
            this,
            R.array.men_tid,
            android.R.layout.simple_spinner_item
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.tidptrSpinner.adapter = adapter
            binding.tidlenSpinner.adapter = adapter
        }
        binding.tidptrSpinner.setSelection(0, true)
        binding.tidlenSpinner.setSelection(6, true)

        // Baud Rate Spinner
        val strBaudRate = arrayOf("57600bps", "115200bps")
        ArrayAdapter(
            this,
            android.R.layout.simple_spinner_item,
            strBaudRate
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.baudSpinner.adapter = adapter
        }
        // Selection is handled in onResume via LiveData observer

        // Dwell Spinner
        val dwellTime = Array(254) { index -> "${index + 2}00ms" }
        ArrayAdapter(
            this,
            android.R.layout.simple_spinner_item,
            dwellTime
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.dwellSpinner.adapter = adapter
        }
        binding.dwellSpinner.setSelection(48, false)

        // Tag Focus Spinner
        ArrayAdapter.createFromResource(
            this,
            R.array.en_select,
            android.R.layout.simple_spinner_item
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.focusSpinner.adapter = adapter
        }
        binding.focusSpinner.setSelection(0, false)

        // Antenna Check Spinner
        ArrayAdapter.createFromResource(
            this,
            R.array.en_select,
            android.R.layout.simple_spinner_item
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.checkantSpinner.adapter = adapter
        }
        binding.checkantSpinner.setSelection(1, false)

        // IvtType Spinner
        ArrayAdapter.createFromResource(
            this,
            R.array.IvtType_select,
            android.R.layout.simple_spinner_item
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.IvtTypeSpinner.adapter = adapter
        }
        binding.IvtTypeSpinner.setSelection(0, false)

        // Memory Spinner
        ArrayAdapter.createFromResource(
            this,
            R.array.readmen_select,
            android.R.layout.simple_spinner_item
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.mixmemSpinner.adapter = adapter
        }
        binding.mixmemSpinner.setSelection(1, false)

        // Range Spinner
        strRange = Array(101) { index -> index.toString() }
        ArrayAdapter(
            this,
            android.R.layout.simple_spinner_item,
            strRange
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.rangeSpinner.adapter = adapter
        }
        binding.rangeSpinner.setSelection(16, false)

        // Profile Spinner
        // Profiles are set up based on ModuleType in setupModuleType()
    }

    private fun setupModuleType() {
        viewModel.ReaderType = RrReader.rrlib.GetReaderType()
        when (viewModel.ReaderType) {
            0x21, 0x28, 0x23, 0x37, 0x36 -> { // R2000
                strProfile = arrayOf(
                    "0:40K, FM0,25us",
                    "1:250K,M4, 25us",
                    "2:300K,M4, 25us",
                    "3:400K,FM0,6.25us"
                )
                viewModel.ModuleType = 1
                binding.lineprogile.visibility = View.VISIBLE
            }
            0x70, 0x71, 0x31 -> { // Ex10
                strProfile = arrayOf(
                    "11:640K,FM0,7.5us",
                    "1:640K, M2,7.5us",
                    "15:640K, M4,7.5us",
                    "12:320K, M2, 15us",
                    "3:320K, M2, 20us",
                    "5:320K, M4, 20us",
                    "7:250K, M4, 20us",
                    "13:160K, M8, 20us",
                    "103:640K,FM0,6.25us",
                    "120:640K, M2,6.25us",
                    "202:426K,FM0, 15us",
                    "345:640K, M4,7.5us"
                )
                viewModel.ModuleType = 2
                binding.linetagfocus.visibility = View.VISIBLE
                binding.lineprogile.visibility = View.VISIBLE
                binding.lineloss.visibility = View.VISIBLE
                binding.linecheckant.visibility = View.VISIBLE
            }
            0x61, 0x63, 0x65, 0x66 -> { // C6
                strProfile = arrayOf(
                    "0:160K,FM0,12.5us",
                    "1:160K, M8,12.5us",
                    "2:250K,FM0,12.5us",
                    "3:320K, M4,6.25us",
                    "4:160K, M4,12.5us"
                )
                viewModel.ModuleType = 3
                binding.lineprogile.visibility = View.VISIBLE
            }
            else -> { // Default to ModuleType 0
                viewModel.ModuleType = 0
                binding.linerange.visibility = View.VISIBLE
            }
        }

        // Set up Profile Spinner
        ArrayAdapter(
            this,
            android.R.layout.simple_spinner_item,
            strProfile
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.profSpinner.adapter = adapter
        }

        if (viewModel.ModuleType == 2) {
            binding.profSpinner.setSelection(5, false)
        } else {
            binding.profSpinner.setSelection(1, false)
        }
    }

    private fun setupObservers() {
        // Observe LiveData from ViewModel and update UI accordingly

        viewModel.version.observe(this, Observer { version ->
            binding.version.text = version
        })

        viewModel.result.observe(this, Observer { result ->
            binding.paramResult.text = result
        })

        viewModel.temp.observe(this, Observer { temp ->
            binding.txtTempe.text = temp
        })

        viewModel.loss.observe(this, Observer { loss ->
            binding.txtLoss.text = loss
        })

        // Spinner selections
        viewModel.powerSelection.observe(this, Observer { position ->
            binding.powerSpinner.setSelection(position, false)
        })

        viewModel.baudRateSelection.observe(this, Observer { position ->
            binding.baudSpinner.setSelection(position, false)
        })

        viewModel.bandSelection.observe(this, Observer { position ->
            binding.bandSpinner.setSelection(position, false)
        })

        viewModel.maxFrmSelection.observe(this, Observer { position ->
            binding.maxSpinner.setSelection(position, false)
        })

        viewModel.minFrmSelection.observe(this, Observer { position ->
            binding.minSpinner.setSelection(position, false)
        })

        viewModel.timeSelection.observe(this, Observer { position ->
            binding.timeSpinner.setSelection(position, false)
        })

        viewModel.qValueSelection.observe(this, Observer { position ->
            binding.qvalueSpinner.setSelection(position, false)
        })

        viewModel.sessionSelection.observe(this, Observer { position ->
            binding.sessionSpinner.setSelection(position, false)
        })

        viewModel.tidAddrSelection.observe(this, Observer { position ->
            binding.tidptrSpinner.setSelection(position, false)
        })

        viewModel.tidLenSelection.observe(this, Observer { position ->
            binding.tidlenSpinner.setSelection(position, false)
        })

        viewModel.dwellSelection.observe(this, Observer { position ->
            binding.dwellSpinner.setSelection(position, false)
        })

        viewModel.tagFocusSelection.observe(this, Observer { position ->
            binding.focusSpinner.setSelection(position, false)
        })

        viewModel.antCheckSelection.observe(this, Observer { position ->
            binding.checkantSpinner.setSelection(position, false)
        })

        viewModel.profileSelection.observe(this, Observer { position ->
            binding.profSpinner.setSelection(position, false)
        })

        viewModel.rangeSelection.observe(this, Observer { position ->
            binding.rangeSpinner.setSelection(position, false)
        })
    }

    override fun onClick(view: View?) {
        when (view) {
            binding.ivtRead -> viewModel.readParam()
            binding.ivtSetting -> {
                // Collect parameters from UI and set them via ViewModel
                val length = binding.tidlenSpinner.selectedItemPosition
                val wordPtr = binding.tidptrSpinner.selectedItemPosition
                val qValue = binding.qvalueSpinner.selectedItemPosition
                val scanTime = binding.timeSpinner.selectedItemPosition
                val ivtType = binding.IvtTypeSpinner.selectedItemPosition
                val memory = binding.mixmemSpinner.selectedItemPosition + 1
                val session = binding.sessionSpinner.selectedItemPosition

                viewModel.setParam(length, wordPtr, qValue, scanTime, ivtType, memory, session)

                if (viewModel.ModuleType == 2) {
                    val jgTimes = binding.jgTimeSpinner.selectedItemPosition
                    val dwell = binding.dwellSpinner.selectedItemPosition
                    // Additional parameters can be set here if needed
                    // For example, setting Interval and other configurations
                }
            }
            binding.proSetting -> {
                // Collect power and frequency settings and set via ViewModel
                val power = binding.powerSpinner.selectedItemPosition
                val fband = binding.bandSpinner.selectedItemPosition
                val band = when (fband) {
                    0 -> 1
                    1 -> 2
                    2 -> 3
                    3 -> 4
                    4 -> 8
                    5 -> 0
                    else -> 0
                }
                val minFre = binding.minSpinner.selectedItemPosition
                val maxFre = binding.maxSpinner.selectedItemPosition

                viewModel.setRfPowerAndRegion(power, band, maxFre, minFre)
            }
            binding.btSetRange -> {
                val index = binding.rangeSpinner.selectedItemPosition
                viewModel.setRange(index)
            }
            binding.btGetRange -> {
                viewModel.getRangeControl()
            }
            binding.btGetantcheck -> {
                viewModel.readCheckAnt()
            }
            binding.btSetantcheck -> {
                val antCheck = binding.checkantSpinner.selectedItemPosition
                viewModel.setAntCheck(antCheck)
            }
            binding.proRead -> {
                viewModel.readInformation()
            }
            binding.btSetBdRate -> {
                val index = binding.baudSpinner.selectedItemPosition
                val baudRate = when (index) {
                    0 -> 57600
                    1 -> 115200
                    else -> 57600
                }
                viewModel.setBaudRate(baudRate)
            }
            binding.btSetFocus -> {
                val index = binding.focusSpinner.selectedItemPosition
                viewModel.setFocus(index)
            }
            binding.btGetFocus -> {
                viewModel.readFocus()
            }
            binding.btReadloss -> {
                viewModel.measureLoss()
            }
            binding.btSetProfile -> {
                val index = binding.profSpinner.selectedItemPosition
                viewModel.setProfile(index)
            }
            binding.btReadtemp -> {
                viewModel.readTemperature() // Implement if applicable
            }
            binding.btReadloss -> {
                viewModel.measureLoss()
            }
            // Handle other button clicks similarly
        }
    }

    override fun onPause() {
        super.onPause()
        // Handle any necessary operations on pause
    }

    override fun onDestroy() {
        super.onDestroy()
        // Handle any necessary cleanup on destroy
    }

    companion object {
        const val TAG = "ScanViewActivity"
    }
}


